package com.shawbs.vueblog.controller;

import com.shawbs.vueblog.comom.Result;
import com.shawbs.vueblog.comom.UploadFileResponse;
import com.shawbs.vueblog.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "通用模块")
@RestController
@RequestMapping("/common")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;
    
    public UploadFileResponse uploadFileHandle(MultipartFile file){
        String fileName = fileService.storeFile(file);

        String fileUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(fileName)
                .toUriString();

        fileUri = "/" + fileUri.replaceAll("http\\S+\\/\\/[^\\/]*/","");

        UploadFileResponse uploadFileResponse = new UploadFileResponse(fileName, fileUri,
                file.getContentType(), file.getSize());

        return uploadFileResponse;
    }

    @ApiOperation(value = "单文件上传")
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file){
        return Result.success(this.uploadFileHandle(file));
    }

    @ApiOperation(value = "多文件上传")
    @PostMapping("/uploadMultipleFiles")
    public Result uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        List<UploadFileResponse> list = Arrays.stream(files)
                .map(this::uploadFileHandle)
                .collect(Collectors.toList());
        return Result.success((list));
    }

    @GetMapping("/downloadFile/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        // Load file as Resource
        Resource resource = (Resource) fileService.loadFileAsResource(fileName);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }
}
